//
//  SKYNetworkSection.m
//  Pods
//
//  Created by Walker on 2016/12/20.
//
//

#import "SKYNetworkSection.h"

@interface SKYNetworkSection()
@property (readwrite, nonatomic, strong) NSURLSession *session;
@end

@implementation SKYNetworkSection

- (instancetype)init {
    if (self = [super init]) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSession sharedSession].configuration delegate:self delegateQueue:[NSURLSession sharedSession].delegateQueue];
        
    }
    return self;
}

+ (instancetype)section {
    SKYNetworkSection *section = [[SKYNetworkSection alloc] init];
    return section;
}

- (NSURLSessionTask *)request:(NSMutableURLRequest *)request completionHandler:(void(^)(NSHTTPURLResponse * _Nullable response, NSData * _Nullable data,NSError * _Nullable error))completionHandler {
    NSURLSessionTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *httpResponse = nil;
        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            httpResponse = (NSHTTPURLResponse *)response;
        }
        if (completionHandler) {
            completionHandler(httpResponse,data,error);
        }
    }];
    [task resume];
    return task;
}

- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
    __block NSArray *tasks = nil;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
        if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
            tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
        }
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return tasks;
}

- (NSArray *)tasks {
    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}


#pragma mark - NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    if (completionHandler) {
        completionHandler(NSURLSessionAuthChallengeUseCredential,nil);
    }
}

@end




